﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ebusiness_Framework.Evebtbus
{
    public static class EvebtbusServiceCollectionExtentions
    {
        /// <summary>
        /// 集成事件总线
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection UseEventBus<_DbContext>(this IServiceCollection services, IConfiguration configuration) where _DbContext : DbContext
        {
            EvebtbusOptions evebtbusOptions = configuration.GetSection("EventBusConfig").Get<EvebtbusOptions>();
            services.AddCap(options =>
            {
                // 2.1、集成DotNetCore.CAP.RabbitMQ
                options.UseRabbitMQ(rb =>
                {
                    //rb.HostName = "192.168.211.129";
                    //rb.UserName = "admin";
                    //rb.Password = "admin123";
                    //rb.Port = 5672;
                    //rb.VirtualHost = "/";

                    rb.HostName = evebtbusOptions.HostName;
                    rb.UserName = evebtbusOptions.UserName;
                    rb.Password = evebtbusOptions.Password;
                    rb.Port = evebtbusOptions.Port;
                    rb.VirtualHost = evebtbusOptions.VirtualHost;
                });

                // 2.2、集成DotNetCore.CAP.InMemoryStorage 本地存储、缓存、本地消息表
                //options.UseInMemoryStorage();

                //集成DotNetCore.CAP.Dashboard 集成 消息控制台
                options.UseDashboard();

                //设置重试次数和重试时间
                options.FailedRetryInterval = evebtbusOptions.FailedRetryInterval;
                options.FailedRetryCount = evebtbusOptions.FailedRetryCount;

                // 5.5 使用EntityFramework进行存储操作
                options.UseEntityFramework<_DbContext>();
                // 5.6 使用UseMySql创建本地消息表，和存储事件
                options.UseMySql(evebtbusOptions.DbConnectionString);
            });
            return services;
        }
    }
}
